package coder.taiji.test.springnetty.tcp.service;

import coder.taiji.test.springnetty.tcp.dto.TestProtocolDTO;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 功能:tcp数据处理层
 *
 * @author helloworldyu
 * @date 2017/10/17
 */
public class TcpServerHandler extends SimpleChannelInboundHandler<TestProtocolDTO> {
	private static final Logger logger = LoggerFactory.getLogger(TcpServerHandler.class);

	/**
	 * 有数据可读的时候触发
	 *
	 * @param ctx 上下文
	 * @param msg 消息
	 */
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TestProtocolDTO msg) {
		//处理消息
		//合法
		ctx.channel().writeAndFlush(msg);
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
		logger.debug("有超时事件发生:{}", ctx.channel().remoteAddress().toString());
	}


	/**
	 * 异常的时候触发
	 *
	 * @param ctx   上下文
	 * @param cause 异常
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		logger.error("{}:异常,栈信息:", ctx.channel().remoteAddress().toString(), cause);
	}
}